package com.atguigu.gulimall.member.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


import com.alibaba.nacos.common.util.Md5Utils;
import com.atguigu.common.exception.ErrorException;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.MD5Util;
import com.atguigu.common.vo.MemberInfoVo;
import com.atguigu.common.vo.MemberRegisterVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;


/**
 * 会员
 *
 * @author HX
 * @email 1624242879@qq.com
 * @date 2021-01-17 21:37:11
 */
@RestController
@RequestMapping("member/member")
public class MemberController {
    @Autowired
    private MemberService memberService;

    /**
     * 会员注册
     */
    @PostMapping("/register")
    public  R register(@RequestBody MemberRegisterVo memberRegisterVo){
        MemberEntity memberEntity=new MemberEntity();
        BeanUtils.copyProperties(memberRegisterVo,memberEntity);
        memberEntity.setMobile(memberRegisterVo.getPhone());
        //设置默认等级
        memberEntity.setLevelId(1L);
        //检查手机号用户是否唯一
        memberService.checkPhoneUsername(memberRegisterVo.getPhone(),memberRegisterVo.getUsername());
        memberEntity.setPassword(MD5Util.encode1(memberRegisterVo.getPassword()));
        memberService.save(memberEntity);
        return  R.ok();
    }


    /**
     * 会员登录
     */
    @GetMapping("/login")
    public  R login(@RequestParam String phone,@RequestParam String password){
       MemberEntity member= memberService.findByPhone(phone);
       BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
       boolean b =encoder.matches(password,member.getPassword());
         if (b){
             return  R.ok();
         }
      return  R.error(2000,"密码错误");
    }
    //社交登录
    @GetMapping("oathu/login")
    public  MemberEntity oathuLogin(@RequestParam  String accessToken) throws Exception {
        Map<String,String> query=new HashMap();
        query.put("access_token",accessToken);
        HttpResponse response = HttpUtils.doGet
                ("https://gitee.com","/api/v5/user","get",new HashMap<String, String>(),query);
        if (response.getStatusLine().getStatusCode()==200){
            String userinfo = EntityUtils.toString(response.getEntity());
            Gson gson = new Gson();
            HashMap info = gson.fromJson(userinfo, HashMap.class);
            Double id = (Double) info.get("id");
            MemberEntity member = memberService.getOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getGiteeId, id));
            if (member!=null){
                //该用户注册过
                MemberEntity update=new MemberEntity();
                update.setId(member.getId());
                update.setNickname((String) info.get("name"));
                update.setUsername((String) info.get("name"));
                update.setHeader((String) info.get("avatar_url"));
                memberService.updateById(update);
                return  update;
            }else {
                //未注册
                MemberEntity save=new MemberEntity();
                save.setNickname((String) info.get("name"));
                save.setUsername((String) info.get("name"));
                save.setHeader((String) info.get("avatar_url"));
                save.setGiteeId(id);
                save.setGender(1);
                memberService.save(save);
                return  save;
            }
        }else {
           return  new MemberEntity();
        }
    }


    //微博登录
    @PostMapping("oathu/weibo")
    public  R  oathuWeiBo(@RequestBody MemberInfoVo vo){
        MemberEntity memberEntity=  memberService.oathuWeiBo(vo);
        if (memberEntity!=null){
            return  R.ok().put("data",memberEntity);
        }else {
            return  R.error(1000,"服务器异常");
           // throw  new ErrorException();
        }
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    // @RequiresPermissions("member:member:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = memberService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    // @RequiresPermissions("member:member:info")
    public R info(@PathVariable("id") Long id) {
        MemberEntity member = memberService.getById(id);

        return R.ok().put("member", member);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //  @RequiresPermissions("member:member:save")
    public R save(@RequestBody MemberEntity member) {
        memberService.save(member);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    // @RequiresPermissions("member:member:update")
    public R update(@RequestBody MemberEntity member) {
        memberService.updateById(member);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    // @RequiresPermissions("member:member:delete")
    public R delete(@RequestBody Long[] ids) {
        memberService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
